<template>
  <div class="connect" v-loading="loading">
    <div class="use_box">
      <el-form :inline="true"   :model="selectForm" class="demo-form-inline">
        <!-- <el-form-item :label="$t('Order_module.Destination_Country_Region')">
          <el-select v-model="value" :placeholder="$t('Order_module.Destination_Country_Region') ">
              <el-option
                v-for="item in selectForm.country"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('Order_module.Recipient_Xing_Name')">
          <!-- 收件人姓名 -->
           <el-input v-model="selectForm.consigneeName" :placeholder="$t('Order_module.Recipient_Xing_Name') "></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.PRINT_STATUS')">
          <!-- 打印状态 -->
          <el-select v-model="selectForm.printStatus" :placeholder="$t('Order_module.PRINT_STATUS') ">
              <el-option
                v-for="item in printStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="$t('Order_module.creation_date')">
          <!-- 开始时间结束时间 -->
          <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="selectForm.Time"
                type="datetimerange"
                @change="pickerOptions_star"
                range-separator="-"
                :start-placeholder="$t('Order_module.Select_Date')"
                :end-placeholder="$t('Order_module.Select_Date')">
              </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('Order_module.User')">
          <!-- 用户下拉 -->
          <el-select v-model="selectForm.customerId" :placeholder="$t('Order_module.User') ">
              <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Batch_number')">
          <!-- 批次号 -->
            <el-input v-model="selectForm.manifestNo" :placeholder="$t('Order_module.Batch_number') "></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Order_No')">
          <!-- 订单号 -->
            <el-input v-model="selectForm.orderNumber" :placeholder="$t('Order_module.Order_No') "></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Waybill_number')">
          <!-- 运单号 -->
            <el-input v-model="selectForm.logisticsNo" :placeholder="$t('Order_module.Waybill_number') "></el-input>
        </el-form-item>
        <el-button type="primary" :loading="searchLoading" @click="searchSubmit">{{$t('public.query')}}</el-button>
        <el-button type="primary" :loading="resetLoading" @click="resetting">{{$t('public.resetting')}}</el-button>
      </el-form>
      <div style="margin-bottom: 20px; display: flex; flex-wrap: wrap;">
        <el-button :loading="Conditional_export_loading"  @click="Conditional_export">{{this.$t('public.Conditional_export')}}</el-button> <!-- 导出 -->
        <el-button :loading="sleect_export_loading"  @click="sleect_export">{{this.$t('public.select_export')}}</el-button> <!-- 导出 -->
        <!-- 这三个一组 -->
        <!-- 更新订单重量模版下载 -->
        <el-button  :loading="weight_down_Loading" @click="weight_down">{{$t('Order_module.Update_order_weight_template_download')}}</el-button>
        <!-- <el-button  type="primary" >{{$t('Order_module.Choose_to_update_the_order_information_table')}}</el-button>
        <el-button  type="success" >{{$t('Order_module.Batch_update_order_information')}}</el-button> -->
        <!-- 其他功能 -->
        <el-upload style="margin-left: 10px; margin-right: 10px;" ref="upload" action="https://jsonplaceholder.typicode.com/posts/"
          :on-change = "beforeupload"
          :show-file-list = "false"
          :file-list="fileList"
          :auto-upload="false">
          <el-button  slot="trigger"  type="primary" >{{$t('Order_module.Choose_to_update_the_order_information_table')}}</el-button>
        </el-upload>
        <el-button v-if="upFile"  type="text" >{{upFile.name}}</el-button>
        <el-button @click="submitFile(upFile)"  type="success" >{{$t('Order_module.Batch_update_order_information')}}</el-button>
        <el-button   :loading="piaoEdit_loading" @click="piaoEdit(null , 1)">{{$t('Order_module.place_an_order')}}</el-button>
      </div>
      <el-table border @selection-change="handleSelectionChange"  tooltip-effect="dark" :data="tableData"
        style="width: 100%">
         <el-table-column type="selection" align="center" width="55"></el-table-column>
         <!-- 批次号 -->
         <el-table-column align="center" prop="manifestNo" :label="$t('Order_module.Batch_number')"  min-width="180"></el-table-column>
         <!-- 订单号 -->
        <el-table-column align="center" prop="orderNumber" :label="$t('Order_module.Order_No')"  min-width="180 "></el-table-column>
        <!-- 快递号 -->
        <el-table-column align="center" prop="logisticsNo" :label="$t('public.logisticsNo')"  min-width="180">
          <template slot-scope="{row}">
            {{row.logisticsNo?row.logisticsNo:'-'}}
          </template>
        </el-table-column>
        <!-- 订单状态 -->
        <el-table-column align="center" prop="orderNumber" :label="$t('public.order_status')"  min-width="120">
          <template slot-scope="{row}">
            <span v-if="row.orderStatus==0">{{$t('public.placed_an_orde')}}</span>
            <span v-if="row.orderStatus==1">{{$t('public.Ordered')}}</span>
            <span v-if="row.orderStatus==2">{{$t('public.Pull_failure')}}</span>
            <span v-if="row.orderStatus==3">{{$t('public.Recycling_Center')}}</span>
            <span v-if="row.orderStatus==4">{{$t('public.Dead')}}</span>
            <span v-if="row.orderStatus==5">{{$t('public.Vendor_confirmation')}}</span>
            <span v-if="row.orderStatus==6">{{$t('public.Service_provider_declaration')}}</span>
            <span v-if="row.orderStatus==7">{{$t('public.Receipt_for_Application')}}</span>
            <span v-if="row.orderStatus==8">{{$t('public.banding_machine_residual')}}</span>
            <span v-if="row.orderStatus==9">{{$t('public.Under_purchase')}}</span>
            <span v-if="row.orderStatus==10">{{$t('public.Received')}}</span>
          </template>
        </el-table-column>
        <!-- 打印状态 -->
        <el-table-column align="center" prop="orderNumber" :label="$t('public.Print_mode')"  min-width="120">
          <template slot-scope="{row}">
            <span v-if="row.printStatus==0">{{$t('public.No_Print_head')}}</span>
            <span v-if="row.printStatus==1">{{$t('public.printed')}}</span>
          </template>
        </el-table-column>

        <!-- 所属用户 -->
        <el-table-column align="center" prop="userName" :label="$t('Order_module.User')"  min-width="120"></el-table-column>
        <!-- 代理名称 -->
        <el-table-column align="center" prop="agentName" :label="$t('public.agentName')"  min-width="120"></el-table-column>
        <!-- 创建时间 -->
        <el-table-column align="center" prop="createTime" :label="$t('Order_module.creation_date')"  min-width="200"></el-table-column>
        <!-- 客户重量 -->
        <el-table-column align="center" prop="userWeight" :label="$t('public.Declared_weight')"  min-width="120"></el-table-column>
        <!-- 京东重量 -->
        <el-table-column align="center" prop="jdWeight" :label="$t('public.JD_Weight')"  min-width="120">
          <template slot-scope="{row}">
            {{row.jdWeight?row.jdWeight:'-'}}
          </template>
        </el-table-column>
        <!-- 包裹数量 -->
        <el-table-column align="center" prop="packageNum" :label="$t('Order_module.Number_of_packages')"  min-width="120"></el-table-column>
        <!-- 发件人 -->
        <el-table-column align="center" prop="senderName" :label="$t('public.Sender_name')"  min-width="120"></el-table-column>
        <!-- 收件人 -->
        <el-table-column align="center" prop="consigneeName" :label="$t('Order_module.Recipient_Xing_Name')"  min-width="120"></el-table-column>
       <!-- 操作 -->
        <el-table-column
            fixed="right"
            align="center"
            :label="$t('public.operate')"
            width="100">
            <template slot-scope="{row}">

              <el-button v-if="row.logisticsNo != ''" @click="seeInfo(row.logisticsNo)" type="text" size="small">{{$t('public.View_logistics')}}</el-button>
              <!-- <el-button  @click="piaoEdit(row.id , 2)" type="text" size="small">{{$t('public.details')}}</el-button> -->
              <el-button v-if="row.logisticsNo==''" @click="piaoEdit(row.id , 2)" type="text" size="small">{{$t('public.modify')}}</el-button>
            </template>
          </el-table-column>
      </el-table>
      <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page   "
            :page-sizes="[10, 50, 100, 200]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </div>
    <el-dialog
      title=""
      :visible.sync="err_show"
      width="30%"
      :before-close="err_showClose">
      <div>
        <div v-for="(item,index) in message" :key="index">{{item}}</div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="err_show = false">{{$t('public.determine')}}</el-button>
      </span>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog :title="$t('public.View_logistics')" :visible.sync="show" width="90%" :before-close="handleClose">
      <div>
        <el-steps :space="90" direction="vertical" :active="0">
            <el-step v-for="(item,index) in trackList"  :key="index" :icon="index==0?'el-icon-location':'el-icon-location-outline'" :title="item.opeTitle">
              <div slot="description">
                <p>{{item.content}}</p>
                <p>{{item.operationTime}}</p>
              </div>
            </el-step>
          </el-steps>
      </div>


    </el-dialog>

    <!-- 单票下单对话框 -->
    <el-dialog
      :title="$t('Order_module.place_an_order')"
      :visible.sync="piaoShow"
      :close-on-click-modal="false"
      top="5vh"
      :before-close="handlepiaoClose">
        <orderInfo v-if="piaoShow" :id="seeInfo_id" @getList="getList"  @closepop = "handlepiaoClose" :piao_type="piao_type" ref="orderInfoRef" ></orderInfo>
    </el-dialog>

  </div>
</template>

<script>
  import {
    order_list,
    order_search,
    order_searchUser,
    address_getDefault,
    order_info,
    order_save,
    order_update,
    orderWeight,
    order_tracking,
    order_conditionalExport,
    order_selectExport,
    order_searchList
  } from '@/api/wqzApi'
  import AddressParse,{AREA, Utils} from 'address-parse';
  import orderInfo from '@/components/order_info';
  import { getToken } from '@/utils/auth'
import axios from 'axios'
  export default {
    components:{
      orderInfo
    },
    data() {
      return {
        piaoEdit_loading:false,
        weight_down_Loading:false,
        Conditional_export_loading:false,
        sleect_export_loading:false,
        searchLoading:false,
        resetLoading:false,//重置loading
        chooseItem:[],
        loading:false,
        message:'',//错误提示内容
        err_show:false,
        fileList:[],//文件上传列表
        senderAddressObj:{ // 发件人地址
          senderName:null,//姓名
          senderProvince:null,//省
          senderCity:null,//城市
          senderCounty:null,//区
          senderAddr:null,//详细地址
          cell_phone_num:null,//手机号
          senderTel:null,//电话号
          senderZip:null,//邮政编码
          Address_Resolution:null,//地址解析
        },
        shopList:[
          {
            goodName:null ,// 物品名称
            goodNumber:null, //物品数量
            goodPrice:null //物品单价
          },
        ],
        piaoShow:false, //单票下单对话框
        show:false,//查看详情对话框
        tableData:[], //订单列表
        list:[ //报关商品信息列表

        ],
        value:'',
        total:100,
        page:1,
        limit:10,
        value2:'2023-11-09',
        printStatusList:[ //打印状态
          {value: 1,label:this.$t('public.printed')},
          {value: 0,label:this.$t('public.No_Print_head')}
        ],
        userList : [], // 所属用户列表
        selectForm:{
          consigneeName:'',//收件人姓名
          customerId:'',//所属用户id
          manifestNo:'',//批次号
          orderNumber:'' , //订单号
          logisticsNo:'',//运单号
          printStatus:'' , //打印状态(0.未打印1.已打印)
          startTime:'' , //开始日期
          endTime:'' , //结束日期
          Time:[],//开始日期和结束日期
        },
        activeName:"1",
        piao_type:null , //1新增订单2编辑订单
        order_id:'',//订单id
        order_info:{},//订单详情
        upFile:null , //当前上传的文件
        trackList:[],//物流信息
        seeInfo_id:0,
      }

    },

    created() {
    },
    mounted() {
       var params = this.$getUrlParams()
       if(params.ids){
         order_searchList(params.ids.split(',')).then(res=>{
           this.tableData = res.list
         })
       }else{
         this.getList()
       }
      this.getUserList()
    },
    destroyed() {

    },
    methods: {
      resetting(){
        this.selectForm = {
          consigneeName:'',//收件人姓名
          customerId:'',//所属用户id
          manifestNo:'',//批次号
          orderNumber:'' , //订单号
          logisticsNo:'',//运单号
          printStatus:'' , //打印状态(0.未打印1.已打印)
          startTime:'' , //开始日期
          endTime:'' , //结束日期
          Time:[],//开始日期和结束日期
        }
        this.resetLoading = true
        this.searchSubmit()
      },
      Conditional_export(){
        // 条件导出
        var formData = new FormData()
        this.Conditional_export_loading = true
        formData.append('consigneeName', this.selectForm.consigneeName)
        formData.append('customerId', this.selectForm.customerId)
        formData.append('manifestNo', this.selectForm.manifestNo)
        formData.append('orderNumber', this.selectForm.orderNumber)
        formData.append('logisticsNo', this.selectForm.logisticsNo)
        formData.append('printStatus', this.selectForm.printStatus)
        formData.append('startTime', this.selectForm.startTime)
        formData.append('endTime', this.selectForm.endTime)
        this.$export_down(order_conditionalExport() , formData , this.$t('route.Order_Status_Management')).then(res=>{
          this.Conditional_export_loading = false
        })
      },
      sleect_export(){
        // 选择导出
        var ids = []
        this.sleect_export_loading = true
         this.chooseItem.forEach((item,index)=>{
          ids.push(item.id)
        })
        if(ids.length<=0){
          this.$message({
            type:'warning',
            message:this.$t('public.Please_select_id'),
          })
          this.sleect_export_loading = false
          return
        }
        this.$export_down(order_selectExport() , ids ,  this.$t('route.Order_Status_Management')).then(res=>{
          this.sleect_export_loading = false
        })
      },
      err_showClose(){
        this.err_show = !this.err_show
      },
      submitFile(files){
        // 创建FormData
        if(!files){
          this.$message({
            type:'warning',
            message:this.$t('Order_module.Choose_to_update_the_order_information_table')
          })
          return
        }
        var formData = new FormData()
        formData.append('file', files)
        var url = process.env.VUE_APP_BASE_API + '/api/order/modifyWeight'
        var  token = getToken()
        // 设置请求头信息
        const headers = {
          'Content-Type': 'multipart/form-data',
          'Token' : token,
          'Lang' : this.$store.getters.language=="zh"?'zh_CN':'ko_KR'
        }
        axios.post(url, formData, {
          headers
        }).then(res => {
          if(res.data.code == 0){
            this.$message({
              type:'success',
              message:this.$t('public.Operation_successful')
            })
            this.getList()
          }else{
            this.message = res.data.msg.split('！')
            this.err_show = true
          }
        })
      },
      beforeupload(files){
        var file = files.raw
        if(file.type == 'application/vnd.ms-excel' || file.type=='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
          this.upFile = file
        }else{
          return false
        }
      },
      handlePreview(file){
      },
      handleRemove(file, fileList) {

      },
      // 模版下载
      weight_down() {
        var url = process.env.VUE_APP_BASE_API + '/api/templatesDown/orderWeight'
        var  token = getToken()
        this.weight_down_Loading = true
        axios({
            url: url,
            method: 'post',
            responseType: 'blob',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Token' : token,
              'Lang' : this.$store.getters.language=="zh"?'zh_CN':'ko_KR'
            }// 重点在于配置responseType: 'blob'
        }).then(res => {
          const name = res.headers['content-disposition'];
                  let fileName = '';
                  if (name) {
                    const str1 = name.replace(' ', '');
                    const arr1 = str1.split(';');
                    arr1.some(item => {
                      if (item.indexOf('filename') != -1) {
                        fileName = item.split('=')[1];
                      }
                      return item.indexOf('filename') != -1;
                    });
                    if (fileName === ''){
                      fileName = this.$t('public.Update_the_order_weight_template')+'.xls'
                    }
                  } else {
                    fileName = this.$t('public.Update_the_order_weight_template')+'.xls'
                  }
            const link = document.createElement('a');  // 创建元素
            let blob = new Blob([res.data]);
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);   // 创建下载的链接
            link.setAttribute('download', decodeURI(decodeURI(fileName)));  // 给下载后的文件命名
            document.body.appendChild(link);
            link.click();  // 点击下载
            document.body.removeChild(link);  //  下载完成移除元素
            window.URL.revokeObjectURL(link.href);  // 释放掉blob对象
            this.weight_down_Loading  = false
        }).catch(_ => {
          this.weight_down_Loading  = false
          this.$message({
            type:'error',
            message:'Download failed'
          })
        });
      },
      piaoEdit(id , type){
        // 订单修改弹出层
        this.piao_type = type
        this.piaoShow = !this.piaoShow
        this.piaoEdit_loading = true
        setTimeout(()=>{
          this.piaoEdit_loading = false
          this.$refs.orderInfoRef.piaoEdit(id , type)
        },100)
      },

      getList(){
        // 获取订单列表
        var data = {
          page:this.page,
          limit:this.limit
        }
        order_list(data).then(res=>{
          this.tableData = res.page.list
          this.total = res.page.totalCount
        })
      },
      getUserList(){
        // 筛选条件的userlist
        order_searchUser({}).then(res=>{
          this.userList = res.users
        })
      },
      searchSubmit(){
        this.searchLoading = true
        var data = JSON.parse(JSON.stringify(this.selectForm))
        if(data.Time){
          delete data.Time
        }
        this.page = 1
        data.page = 1
        data.limit = this.limit
        order_search(data).then(res=>{
          this.searchLoading = false
          this.resetLoading = false
          this.tableData = res.page.list
          this.total = res.page.totalCount
          this.$message({
            type:'success',
            message:this.$t('public.Operation_successful')
          })
        }).catch(err=>{
          this.searchLoading = false
          this.resetLoading = false
        })
      },
      handleClick(tab , event){
        console.log(tab , event)
      },
      pickerOptions_star(e){
        // 选择订单穿件时间
        if(e==null){
          this.selectForm.Time = e
          this.selectForm.startTime = ''
          this.selectForm.endTime = ''
        }else{
          this.selectForm.Time = e
          this.selectForm.startTime = e[0]
          this.selectForm.endTime = e[1]
        }

      },
      handleClose(){
        this.show = !this.show
      },
      handlepiaoClose(){
        this.piaoShow = !this.piaoShow
      },
      handleSelectionChange(e){
        console.log(e)
        this.chooseItem = e
      },
      handleSizeChange(e){
        this.limit = e
        this.page = 1
        this.getList()
      },
      handleCurrentChange(e){
        this.page = e
        var data = JSON.parse(JSON.stringify(this.selectForm))
        if(data.Time){
          delete data.Time
        }
        data.page = e
        data.limit = this.limit
        order_search(data).then(res=>{
          this.tableData = res.page.list
          this.total = res.page.totalCount
          this.$message({
            type:'success',
            message:this.$t('public.Operation_successful')
          })
        }).catch(err=>{
        })
        // this.getList()
      },
      seeInfo(id){
        this.loading = true
        order_tracking({logisticsNo:id}).then(res=>{
          this.trackList = res.trackList
          if(res.trackList.length==0){
            this.$message({
              message:this.$t('public.No_logistics_information_available')
            })
            this.loading = false
            return
          }
          this.show = !this.show
          this.loading = false
        }).catch(err=>{
          console.log(err , '返回错误')
          this.loading = false
        })

      }


    }
  }
</script>

<style>
  .use_box{
    background-color: #fff;
    padding: 15px;
    box-sizing: border-box;
  }
  .senderAddress_title{
    font-size: .9vw;
    margin-bottom: 1vw;
  }
</style>
